package com.music.download.perform;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.setting.dialect.Props;
import com.alibaba.fastjson.JSON;
import com.music.download.crawler.CrawlerUtil;
import org.junit.Test;

import java.util.List;
import java.util.Map;

/**
 * 网易云歌单，歌词下载
 * @author zhangby
 * @date 2018/1/31 上午9:45
 */
public class MusicDownLoad4PlayList implements MusicDownInterface {
    public static void main(String[] args) throws Exception {
        new MusicDownLoad4PlayList().downLrc();
    }

    @Test
    public void down() {
        Props props = PropUtil.getInstance();
        String url = StrUtil.format("http://music.163.com/api/song/media?id={}", "34723470");
        String post = HttpUtil.post(url, Dict.create());
        Map map = JSON.parseObject(post, Map.class);
        if (ObjectUtil.isNotNull(map) && ObjectUtil.isNotNull(map.get("lyric"))) {
            String lyric = map.get("lyric").toString();
            String filename = props.get("down_path") + "东京不太热.lrc";
            FileUtil.writeString(lyric, filename, "utf-8");
            System.out.println(filename);
        }
    }

    /** 解析歌曲下载 */
    @Override
    public void downLrc() throws Exception {
        Props props = PropUtil.getInstance();
        //爬去链接
        List<Dict> playList = CrawlerUtil.clawler(props.getStr("playList"));
        playList.forEach(dict -> {
            String url = StrUtil.format("http://music.163.com/api/song/media?id={}", dict.get("id"));
            String post = HttpUtil.post(url, Dict.create());
            Map map = JSON.parseObject(post, Map.class);
            if (ObjectUtil.isNotNull(map) && ObjectUtil.isNotNull(map.get("lyric"))) {
                String lyric = map.get("lyric").toString();
                String filename = props.get("down_path") + dict.get("name").toString() + ".lrc";
                FileUtil.writeString(lyric, filename, "utf-8");
                System.out.println(filename);
            }
        });
    }
}
